package com.wt.struggle.goodbye.main.activity

import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.sina.weibo.sdk.share.WbShareHandler
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ItemClickListener
import com.wt.struggle.goodbye.base.Send
import com.wt.struggle.goodbye.base.Share
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.ShareInfo
import com.wt.struggle.goodbye.info.VideoInfo
import com.wt.struggle.goodbye.main.adapter.ShareLoadAdapter
import com.wt.struggle.goodbye.user.activity.LoginActivity
import com.wt.struggle.goodbye.wxapi.WXEntryActivity
import com.wt.struggle.goodbye.wxutil.Contact
import com.wt.struggle.goodbye.wxutil.QQUtils
import com.wt.struggle.goodbye.wxutil.ShareUtil
import com.xin.lv.yang.utils.info.HttpInfo
import com.xin.lv.yang.utils.utils.DataUtil
import com.xin.lv.yang.utils.utils.FileUtils
import com.xin.lv.yang.utils.utils.ImageUtil
import com.xin.lv.yang.utils.view.CustomProgressDialog
import com.xin.lv.yang.utils.view.CustomToast
import kotlinx.android.synthetic.main.share_layout.*
import org.json.JSONObject

/**
 * 分享界面
 */
class ShareActivity : AppCompatActivity() {

    var send: Send? = null

    /**
     * 是否使用新的列表
     */
    var isNew = true

    /**
     *  1 为不可删除     2 删除我发布的帖子    3 删除历史记录   4 为删除我发布的评论
     */
    var code: Int? = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        send = Send(this)

        setFinishOnTouchOutside(true)
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        val lp: WindowManager.LayoutParams = window.attributes
        //设置窗口宽度
        lp.width = getW()
        //设置窗口高度
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        //设置Dialog位置
        lp.gravity = Gravity.BOTTOM

        Log.i("result", "lp-------" + lp.width)

        window.attributes = lp

        setContentView(R.layout.share_layout)

        shareLinear.layoutParams = FrameLayout.LayoutParams(getW(), FrameLayout.LayoutParams.WRAP_CONTENT)

        code = intent.getIntExtra("code", 1)

        info = intent.getParcelableExtra("info")

        videoList = intent.getParcelableArrayListExtra<VideoInfo>("videoList")
        audioList = intent.getParcelableArrayListExtra<VideoInfo>("voiceList")

        initAdapter()

        tvShareCancel.setOnClickListener {
            finish()
        }

    }

    var info: NewsInfo? = null

    var videoList: ArrayList<VideoInfo>? = null
    var audioList: ArrayList<VideoInfo>? = null


    fun getW(): Int {
        val att = windowManager.defaultDisplay;
        return att.width
    }

    fun getH(): Int {
        val att = windowManager.defaultDisplay;
        return att.height
    }


    val titleArr = arrayListOf<String>(
        "微信好友", "朋友圈", "微博",
        "QQ好友", "QQ空间", "生成分享图",
        "复制链接", "不感兴趣", "查看评论", "删除"
    )

    val newTitleArr = arrayListOf<String>(
        "微信好友", "朋友圈", "QQ好友",
        "生成分享图", "复制链接", "删除"
    )

    val isNewPic = arrayListOf<Int>(
        R.drawable.weichat_pic, R.drawable.wei_chat_friend, R.drawable.qq_pic,
        R.drawable.share_pic1, R.drawable.share_pic2, R.drawable.share_pic4
    )

    val picArr = arrayListOf<Int>(
        R.drawable.weichat_pic, R.drawable.wei_chat_friend, R.drawable.sina_pic,
        R.drawable.qq_pic, R.drawable.qq_zone, R.drawable.share_pic1,
        R.drawable.share_pic2, R.drawable.share_pic3, R.drawable.share_pic4, R.drawable.share_pic4
    )


    private fun initAdapter() {

        val list = arrayListOf<ShareInfo>()

        if (isNew) {

            shareRecyclerView.layoutManager = GridLayoutManager(this, 3)

            val len = when (code) {
                1 -> newTitleArr.size - 2
                2, 3 -> newTitleArr.size - 1
                else -> newTitleArr.size - 2
            }

            for (i in 0..len) {
                val info = ShareInfo()
                info.title = newTitleArr[i]
                info.initPic = isNewPic[i]
                list.add(info)
            }

        } else {
            val len = when (code) {
                1 -> titleArr.size - 2
                2, 3 -> titleArr.size - 1
                else -> titleArr.size - 2
            }

            for (i in 0..len) {
                val info = ShareInfo()
                info.title = titleArr[i]
                info.initPic = picArr[i]
                list.add(info)
            }

            shareRecyclerView.layoutManager = GridLayoutManager(this, 5)
        }

        val adapter = ShareLoadAdapter(this, list)
        shareRecyclerView.adapter = adapter

        adapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {
                if (isNew) {
                    shareNew(position)
                } else {
                    onShare(position)
                }

            }

            override fun onLongClick(position: Int) {

            }

        }
    }


    private fun shareNew(position: Int) {
        val pics = info!!.pics

        val url = if (pics != null && pics != "" && pics != "null" && pics.contains(",")) {
            val arr = pics.split(",")
            Config.GET_IMAGE_URL + arr[0]
        } else {
            Config.GET_IMAGE_URL + pics
        }

        val shareUrl="${Config.IP}/wap/content/contentDetail?id=${info!!.id}&uuid=${Share.getUUID(this)}"

        val shareInfo = ShareInfo()
        shareInfo.title = resources.getString(R.string.app_name)
        shareInfo.content = info!!.content!!
        shareInfo.picUrl = url
        shareInfo.imageUrl=url
        shareInfo.url = shareUrl
        shareInfo.initPic = R.mipmap.logo_small

        when (position) {
            0 -> {
                shareCode = 1
                ShareUtil.share(this, shareInfo, 1)
                saveShare(url,shareUrl)
            }
            1 -> {
                shareCode = 2
                ShareUtil.share(this, shareInfo, 2)
                saveShare(url,shareUrl)
            }
            2 -> {
                shareCode = 3
                saveShare(url,shareUrl)
                ShareUtil.shareToQQUser(
                    this,
                    Tencent.createInstance(Contact.QQ_APP_ID, this),
                    shareInfo,
                    object : IUiListener {
                        override fun onComplete(p0: Any?) {
                        }

                        override fun onCancel() {
                        }

                        override fun onError(p0: UiError?) {
                        }

                    })
            }

            3 -> createSharePic()

            4 -> {
                copy(this, shareUrl)
                showToastShort("复制成功，请去浏览器打开!!")
            }
            else -> {
                deleteTie()
            }
        }

        WXEntryActivity.setOnShareCallBack {
            when(it){
                0->{
                    showToastShort("分享成功")
                  finish()
                }
            }

        }

    }

    var shareCode = 0

    private fun onShare(position: Int) {

        val pics = info!!.pics

        val url = if (pics != null && pics != "" && pics != "null" && pics.contains(",")) {
            val arr = pics.split(",")
            Config.GET_IMAGE_URL + arr[0]
        } else {
            Config.GET_IMAGE_URL + pics
        }

        val shareUrl="${Config.IP}/wap/content/contentDetail?id=${info!!.id}&uuid=${Share.getUUID(this)}"
        val shareInfo = ShareInfo()
        shareInfo.title = resources.getString(R.string.app_name)
        shareInfo.content = info!!.content!!
        shareInfo.imageUrl = url
        shareInfo.picUrl=url
        shareInfo.url = shareUrl
        shareInfo.initPic = R.drawable.pic1

        when (position) {
            0 -> {
                shareCode = 1
                ShareUtil.share(this, shareInfo, 1)
                saveShare(url,shareUrl)
            }
            1 -> {
                shareCode = 2
                ShareUtil.share(this, shareInfo, 2)
                saveShare(url,shareUrl)
            }
            2 -> {
                shareCode = 5
                ShareUtil.shareToSina(this, WbShareHandler(this), shareInfo)
                saveShare(url,shareUrl)
            }
            3 -> {
                shareCode = 3
                saveShare(url,shareUrl)
                ShareUtil.shareToQQUser(
                    this,
                    Tencent.createInstance(Contact.QQ_APP_ID, this),
                    shareInfo,
                    object : IUiListener {
                        override fun onComplete(p0: Any?) {
                        }

                        override fun onCancel() {
                        }

                        override fun onError(p0: UiError?) {
                        }

                    })
            }
            4 -> {
                shareCode = 4
                saveShare(url,shareUrl)
                ShareUtil.shareToQQZone(
                    this,
                    Tencent.createInstance(Contact.QQ_APP_ID, this),
                    shareInfo,
                    object : IUiListener {
                        override fun onComplete(p0: Any?) {
                        }

                        override fun onCancel() {
                        }

                        override fun onError(p0: UiError?) {
                        }

                    })
            }
            5 -> createSharePic()
            6 -> copy(this, shareUrl)
            7 -> disLike()
            8 -> juBao()

            else -> {
                deleteTie()
            }

        }

    }


    private var loadDialog: CustomProgressDialog? = null

    /**
     * 创建加载框
     */
    fun showLoadDialog(string: String = "加载中") {
        if (loadDialog == null) {
            loadDialog = CustomProgressDialog(this)
        }

        loadDialog!!.setText(string)
        loadDialog!!.show()

    }


    /**
     * 移除加载框
     */
    fun removeLoadDialog() {
        if (loadDialog != null && loadDialog!!.isShowing && !this.isFinishing) {
            loadDialog!!.dismiss()
        }
    }

    /**
     * 分享
     */
    private fun saveShare(picUrl: String,shareUrl:String) {
        val list = arrayListOf<HttpInfo>()
        list.add(HttpInfo("platform", shareCode.toString()))
        list.add(HttpInfo("type", "1"))
        list.add(HttpInfo("content_id", info!!.id.toString()))
        list.add(HttpInfo("url", shareUrl))
        list.add(HttpInfo("pics", picUrl))
        send!!.baseHttp("share/addShare", list, 666, handler)
        showLoadDialog("分享中")


    }

    val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val str = msg!!.obj as String
            when (msg.what) {

                Send.DELETE_TIE -> {

                    removeLoadDialog()

                    val json = JSONObject(str)
                    val jsonObject = json.optJSONObject("head")

                    if (jsonObject != null) {

                        val resultCode = jsonObject.optInt("response_status")
                        val resultMessage = jsonObject.optString("response_msg")

                        when (resultCode) {

                            Config.SUCCESS -> {
                                CustomToast.showToast(this@ShareActivity, Gravity.CENTER, 0, "删除成功")
                                setResult(Activity.RESULT_OK)
                                finish()
                            }

                            Config.NO_LOGIN -> {
                                CustomToast.showToast(this@ShareActivity, Gravity.CENTER, 0, resultMessage)
                                startActivity(Intent(this@ShareActivity, LoginActivity::class.java))
                            }
                        }
                    }
                }

                Send.COLLECT_CODE -> {
                    val json = JSONObject(str)
                    val jsonObject = json.optJSONObject("head")

                    if (jsonObject != null) {
                        val resultCode = jsonObject.optInt("response_status")
                        val resultMessage = jsonObject.optString("response_msg")

                        if (resultCode == Config.SUCCESS) {
                            showToastShort(resultMessage)
                            finish()
                        }
                    }
                }

                666 -> {
                    removeLoadDialog()
                }
            }

        }
    }


    fun showToastShort(s: String) {
        CustomToast.showToast(this, Gravity.CENTER, 0, s)

    }

    /**
     * 删除帖子
     */
    private fun deleteTie() {
        val build = AlertDialog.Builder(this)
        build.setTitle("提示").setMessage("是否删除?")
            .setPositiveButton("删除") { _, _ ->

                if (code == 2) {
                    send!!.deleteTie(info!!.id, handler)
                } else if (code == 3) {
                    send!!.deleteHistoryRecord(info!!.id!!, handler)

                }else if(code==4){

                }

                showLoadDialog("删除中")

            }.setNegativeButton("取消") { _, _ -> }
            .show()

    }

    /**
     * 举报 或者查看评论
     */
    private fun juBao() {
        val intent = Intent(this, CommentListActivity::class.java)
        intent.putExtra("info", info)

        intent.putParcelableArrayListExtra("vvvvList", info!!.videoList)
        intent.putParcelableArrayListExtra("audioList", info!!.audioList)

        startActivity(intent)

        finish()

    }

    /**
     * 不感兴趣
     */
    private fun disLike() {
        send!!.unLikeZan(info!!.id!!, 1, handler)
    }


    /**
     * 复制信息到剪切板
     */
    fun copy(context: Context, text: String) {
        val manager: ClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        manager.text = text

    }

    /**
     * 生成分享图
     */
    private fun createSharePic() {

        val url = "${Config.IP}/wap/content/contentDetail?id=${info!!.id}&uuid=${Share.getUUID(this)}"

        val filePath = FileUtils.getCachePath(this) + System.currentTimeMillis() + ".png"

        val b = ImageUtil.getInstance().createQRImage(url, 500, 500, null, filePath)

        if (b) {

            val bitmap = ImageUtil.getInstance().qrBitmap

            val view: View = layoutInflater.inflate(R.layout.qr_image, null)
            val imageClose = view.findViewById<ImageView>(R.id.imageClose)
            val imageQr = view.findViewById<ImageView>(R.id.imageQr)
            imageQr.setImageBitmap(bitmap)
            val build = AlertDialog.Builder(this)
            build.setView(view)
            val qrDialog: Dialog = build.create()
            qrDialog.show()

            imageClose.setOnClickListener {
                qrDialog.dismiss()
            }
        }


    }

}